﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Drawing.Imaging;
using System.Web;

namespace FY2013.Business
{

    public class VerifyCodeGenerator
    {
        public static byte[] CreateImage(string text)
        {
            Bitmap bitmap = new Bitmap(90, 26);
            string randomText = text;
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.FillRectangle(Brushes.WhiteSmoke, 0, 0, 90, 26);
                g.SmoothingMode = SmoothingMode.Default;
                g.TextRenderingHint = TextRenderingHint.AntiAlias;

                Random random = new Random();
                for (int i = 0; i < randomText.Length; i++)
                {
                    Font drawFont = new Font("Arial", 15, FontStyle.Italic | (random.Next() % 2 == 0 ? FontStyle.Bold : FontStyle.Regular));

                    g.DrawString(randomText.Substring(i, 1), drawFont, Brushes.Black, i * 20, random.Next() % 8);

                    Point[] pt = new Point[8];
                    for (int j = 0; j < 8; j++)
                    {
                        pt[j] = new Point(random.Next() % 100, random.Next() % 35);
                        g.DrawEllipse(Pens.LightSteelBlue, pt[j].X, pt[j].Y, random.Next() % 30 + 1, random.Next() % 30 + 1);
                    }
                }
            }

            Byte[] imageBuffer=null;
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
                imageBuffer = stream.GetBuffer();
                bitmap.Dispose();
               // image = Image.FromStream(stream);
            }

            return imageBuffer;
        }

        public static string GetRandomText()
        {
            Random random = new Random();
            string randomText = string.Empty;

            for (int i = 0; i < 4; i++)
            {
                char ch = (char)random.Next(65,90);
                randomText += ch.ToString();
            }
            return randomText;
        }

    }
}
